package customer

import (
	"context"
	"encoding/json"
	"group-card/api/internal/svc"
	"group-card/api/internal/types"
	"group-card/common/response"
	"group-card/common/tool"
	"group-card/rpc/sys/sysclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CustomerAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCustomerAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CustomerAddLogic {
	return &CustomerAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CustomerAddLogic) CustomerAdd(req *types.AddCustomerRequest) (resp *types.CustomerResponse, err error) {

	if !tool.VerifyMobileFormat(req.MobilePhone) {
		return &types.CustomerResponse{Code: response.ErrCode, Message: "请输入正确的手机号格式"}, nil
	}

	if !tool.ValidateMailFormat(req.Email) {
		return &types.CustomerResponse{Code: response.ErrCode, Message: "请输入正确的邮箱格式"}, nil
	}

	_, err = l.svcCtx.Sys.CustomerAdd(l.ctx, &sysclient.CustomerAddRequest{
		Name:          req.Name,
		MobilePhone:   req.MobilePhone,
		LandlinePhone: req.LandlinePhone,
		Area:          req.Area,
		Address:       req.Address,
		Email:         req.Email,
		BeginTimes:    req.BeginTimes,
		EndTimes:      req.EndTimes,
		Status:        req.Status,
	})

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("添加集团客户失败,参数:%s,异常:%s", reqStr, err.Error())
		return &types.CustomerResponse{Code: response.ErrCode, Message: "添加集团客户失败"}, nil
	}

	return &types.CustomerResponse{
		Code:    response.SuccessCode,
		Message: "添加集团客户成功",
	}, nil

}
